package com.quectel.core.module.alarm.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.alarm.dao.AlarmEventConfigDao;
import com.quectel.core.module.alarm.dao.AlarmEventPushUserDao;
import com.quectel.core.module.alarm.dto.AlarmEventConfigDto;
import com.quectel.core.module.alarm.dto.AlarmEventPushUserDto;
import com.quectel.core.module.alarm.dto.AlarmRuleDto;
import com.quectel.core.module.alarm.entity.AlarmEventConfigEntity;
import com.quectel.core.module.alarm.entity.AlarmEventPushUserEntity;
import com.quectel.core.module.alarm.service.AlarmEventConfigService;
import com.quectel.core.module.alarm.service.AlarmEventPushUserService;
import com.quectel.core.module.alarm.service.AlarmRuleService;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.core.module.device.service.DeviceTypeService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author jingyanmao
 * @date 2019-08-29 09:21:34
 */
@DubboService
public class AlarmEventConfigServiceImpl implements AlarmEventConfigService {

    private static final Logger LOGGER = LoggerFactory.getLogger(AlarmEventConfigServiceImpl.class);

    @Autowired
    private AlarmEventConfigDao alarmEventConfigDao;
    @Autowired
    private AlarmEventPushUserDao alarmEventPushUserDao;
    @Autowired
    private DeviceTypeService deviceTypeService;
    @Autowired
    private AlarmRuleService alarmRuleService;
    @Autowired
    private AlarmEventPushUserService alarmEventPushUserService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private VillageService villageService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(AlarmEventConfigDto alarmEventConfigDto) {
        if (alarmEventConfigDto.getId() == null) {
            Long id = save(alarmEventConfigDto);
            alarmEventConfigDto.setId(id);
        } else {
            updateById(alarmEventConfigDto);
        }
        alarmEventPushUserDao.delete(new LambdaQueryWrapper<AlarmEventPushUserEntity>()
                .eq(AlarmEventPushUserEntity::getAlarmEventConfigId, alarmEventConfigDto.getId()));
        if (alarmEventConfigDto.getPushSysUserIds() != null) {
            for (Long pushSysUserId : alarmEventConfigDto.getPushSysUserIds()) {
                AlarmEventPushUserDto alarmEventPushUserDto = new AlarmEventPushUserDto();
                alarmEventPushUserDto.setAlarmEventConfigId(alarmEventConfigDto.getId());
                alarmEventPushUserDto.setSysUserId(pushSysUserId);
                alarmEventPushUserService.save(alarmEventPushUserDto);
            }
        }
    }

    @Override
    public List<AlarmEventConfigDto> selectCacheByDeviceAttr(Long tenantId, Long villageId, Long deviceTypeId) {
        return CacheKit.cacheToRedis(
                () -> {
                    List<AlarmEventConfigEntity> entityList = alarmEventConfigDao.selectList(new LambdaQueryWrapper<AlarmEventConfigEntity>()
                            .eq(AlarmEventConfigEntity::getTenantId, tenantId)
                            .eq(AlarmEventConfigEntity::getVillageId, villageId)
                            .eq(AlarmEventConfigEntity::getDeviceTypeId, deviceTypeId)
                            .eq(AlarmEventConfigEntity::getStatus, SystemConstants.NORMAL)
                    );
                    return CopyUtils.copyList(entityList, AlarmEventConfigDto.class);
                },
                String.format(RedisCacheConstants.DEVICE_ALARM_EVENT_CONFIGS + "%d:%d:%d", tenantId, villageId, deviceTypeId),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public List<AlarmEventConfigDto> queryList(Map<String, Object> params) {
        List<AlarmEventConfigEntity> list = alarmEventConfigDao.queryList(params);
        List<AlarmEventConfigDto> result = CopyUtils.copyList(list, AlarmEventConfigDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return alarmEventConfigDao.queryTotal(params);
    }

    @Override
    public Long save(AlarmEventConfigDto dto) {
        AlarmEventConfigEntity entity = CopyUtils.copyObj(dto, AlarmEventConfigEntity.class);
        entity.setId(Snowflake.nextId());
        alarmEventConfigDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(AlarmEventConfigDto dto) {
        AlarmEventConfigEntity entity = CopyUtils.copyObj(dto, AlarmEventConfigEntity.class);
        alarmEventConfigDao.updateById(entity);
    }

    @Override
    public AlarmEventConfigDto selectById(Long id) {
        AlarmEventConfigEntity entity = alarmEventConfigDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, AlarmEventConfigDto.class));
    }

    private AlarmEventConfigDto paddingField(AlarmEventConfigDto alarmEventConfigDto) {
        if (alarmEventConfigDto == null) {
            return null;
        }
        if (alarmEventConfigDto.getVillageId() != null) {
            VillageDto villageDto = villageService.selectCacheById(alarmEventConfigDto.getVillageId());
            if (villageDto != null) {
                alarmEventConfigDto.setVillageName(villageDto.getName());
            }
        }
        if (alarmEventConfigDto.getDeviceTypeId() != null) {
            if (alarmEventConfigDto.getAlarmRuleIds() != null) {
                List<AlarmRuleDto> alarmRuleDtoList = new ArrayList<>();

                List<Long> alarmRuleIdList = JacksonUtils.parseArray(alarmEventConfigDto.getAlarmRuleIds(), Long.class);
                for (Long ruleId : alarmRuleIdList) {
                    AlarmRuleDto alarmRuleDto = alarmRuleService.selectById(ruleId);
                    if (alarmRuleDto != null) {
                        alarmRuleDtoList.add(alarmRuleDto);
                    }
                }
                alarmEventConfigDto.setAlarmRuleDtoList(alarmRuleDtoList);

            }
        }
        return alarmEventConfigDto;

    }

    @Override
    public void deleteById(Long id) {
        alarmEventConfigDao.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
